# -*- coding: utf-8 -*-
import base64
import datetime
import os
import sys
from time import sleep
import re
import requests
from PIL import Image
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import json

sys.setrecursionlimit(1000000)
# chrome_options 初始化选项
chrome_options = webdriver.ChromeOptions()
# 设置浏览器初始 位置x,y & 宽高x,y
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument(f'--window-position={217},{92}')
chrome_options.add_argument(f'--window-size={1222},{816}')
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
# chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
# chrome_options.add_argument('–headless')
desired_capabilities = DesiredCapabilities.CHROME  # 修改页面加载策略
desired_capabilities["pageLoadStrategy"] = "none"
driver = webdriver.Chrome(options=chrome_options)

# with open('stealth.min.js') as f:
#     js = f.read()
# driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
#   "source": js
# })
driver.set_page_load_timeout(20)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
})
wait = WebDriverWait(driver, 20)


def main():
    driver.get('https://www.meituan.com/changecity/')
    driver.find_element_by_xpath('//div[@class="province-choose"]').click()
    sleep(1)
    driver.find_element_by_xpath('//div[@class="province-col"][1]/span[11]').click()
    sleep(1)
    lit1 = []
    for i in driver.find_elements_by_xpath('//a[@class="link mt-city"]'):
        lit1.append(i.get_attribute('text').strip())

    driver.find_element_by_xpath('//div[@class="province-choose"]').click()
    sleep(1)
    driver.find_element_by_xpath('//div[@class="province-col"][3]/span[9]').click()
    sleep(1)
    for i in driver.find_elements_by_xpath('//a[@class="link mt-city"]'):
        lit1.append(i.get_attribute('text').strip())

    driver.find_element_by_xpath('//div[@class="province-choose"]').click()
    sleep(1)
    driver.find_element_by_xpath('//div[@class="province-col"][3]/span[8]').click()
    sleep(1)
    for i in driver.find_elements_by_xpath('//a[@class="link mt-city"]'):
        lit1.append(i.get_attribute('text').strip())
    return lit1
    # print(len(lit))


def main1():
    global lit
    driver.get('https://www.meituan.com/changecity/')
    for i in range(1, 13):
        driver.find_element_by_xpath('//div[@class="province-choose"]').click()
        sleep(1)
        ci = driver.find_element_by_xpath('//div[@class="province-col"][1]/span[{}]'.format(i)).text
        driver.find_element_by_xpath('//div[@class="province-col"][1]/span[{}]'.format(i)).click()
        if ci == '新疆':
            print('跳过新疆')
            continue
        sleep(1)
        for j in driver.find_elements_by_xpath('//a[@class="link mt-city"]'):
            lit.append(ci + ':' + j.get_attribute('text').strip())

    for i in range(1, 13):
        driver.find_element_by_xpath('//div[@class="province-choose"]').click()
        sleep(1)
        ci = driver.find_element_by_xpath('//div[@class="province-col"][2]/span[{}]'.format(i)).text
        driver.find_element_by_xpath('//div[@class="province-col"][2]/span[{}]'.format(i)).click()
        sleep(1)
        for j in driver.find_elements_by_xpath('//a[@class="link mt-city"]'):
            lit.append(ci + ':' + j.get_attribute('text').strip())

    for i in range(1, 11):
        driver.find_element_by_xpath('//div[@class="province-choose"]').click()
        sleep(1)
        ci = driver.find_element_by_xpath('//div[@class="province-col"][3]/span[{}]'.format(i)).text
        driver.find_element_by_xpath('//div[@class="province-col"][3]/span[{}]'.format(i)).click()
        if ci == '西藏' or ci == '内蒙古':
            print('跳过西藏or内蒙古')
            continue
        sleep(1)
        for j in driver.find_elements_by_xpath('//a[@class="link mt-city"]'):
            lit.append(ci + ':' + j.get_attribute('text').strip())
    print(lit)
    print(len(lit))
    with open('cityid1.txt', 'w+') as f:
        for i in lit:
            f.write(i + '\n')


def yzm():
    driver.get('http://meishi.meituan.com/i/?ci=30&stid_b=1&cevent=imt%2Fhomepage%2Fcategory1%2F1')
    print(driver.title)
    baidu_img = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#yodaImgCode'))
    )
    driver.save_screenshot("screenshot.png")  # 对整个浏览器页面进行截图
    left = baidu_img.location['x']
    top = baidu_img.location['y']
    right = baidu_img.location['x'] + baidu_img.size['width']
    bottom = baidu_img.location['y'] + baidu_img.size['height']

    im = Image.open('screenshot.png')
    im = im.crop((left, top, right, bottom))  # 对浏览器截图进行裁剪
    im.save('baidu.png')
    from aip import AipOcr
    APP_ID = ''  # 刚才获取的 ID，下同
    API_KEY = ''
    SECRECT_KEY = ''
    client = AipOcr(APP_ID, API_KEY, SECRECT_KEY)
    i = open(r'baidu.png', 'rb')
    img = i.read()
    message = client.basicAccurate(img)
    print(message)
    print(message['words_result'][0]['words'])
    if len(message['words_result'][0]['words']) != 4:
        return yzm()
    driver.find_element_by_xpath('//input[@id="yodaImgCodeInput"]').send_keys(message['words_result'][0]['words'])
    sleep(1)
    driver.find_element_by_xpath('//input[@id="yodaImgCodeSure"]').click()


def base64_api(uname, pwd, img, typeid):
    with open(img, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        b64 = base64_data.decode()
    data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]


if __name__ == '__main__':
    yzm()
